class TasksController < ApplicationController
  protect_from_forgery :only => [:create, :update, :destroy]

  # GET /tasks
  # GET /tasks.xml
  def index
    @startdate = ( params[:date] ) ? Date.parse(params[:date]) : Date.today
	@tasks = Task.tasks_by_hour(session[:user_id], @startdate.at_beginning_of_week)
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @tasks }
    end
  end

  # GET /tasks/1
  # GET /tasks/1.xml
  def show
    @task = Task.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @task }
    end
  end

  # GET /tasks/new
  # GET /tasks/new.xml
  def new
    @task = Task.new
	@task.user_id = session[:user_id]

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @task }
    end
  end

  # GET /tasks/1/edit
  def edit
    @task = Task.find(params[:id])
  end

  # POST /tasks
  # POST /tasks.xml
  def create
    @task = Task.new(params[:task])

    respond_to do |format|
      if @task.save
        flash[:notice] = 'Task was successfully created.'
        format.html { redirect_to(@task) }
        format.xml  { render :xml => @task, :status => :created, :location => @task }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @task.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /tasks/1
  # PUT /tasks/1.xml
  def update
    @task = Task.find(params[:id])

    respond_to do |format|
      if @task.update_attributes(params[:task])
        flash[:notice] = 'Task was successfully updated.'
        format.html { redirect_to(@task) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @task.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /tasks/1
  # DELETE /tasks/1.xml
  def destroy
    @task = Task.find(params[:id])
    @task.destroy

    respond_to do |format|
      format.html { redirect_to(tasks_url) }
      format.xml  { head :ok }
    end
  end
  
  
  # GET /tasks/auto
  def autocomplete
	@users = User.find(:all, 
	                    :conditions => [ 'LOWER(CONCAT(lastname," ",firstname)) LIKE ? AND role_id = ?','%' + params[:search][:name].downcase + '%' , Role.patient], 
						:order => 'lastname ASC, firstname ASC',
						:limit => 12)
	render :partial => "autocomplete_user_list" 
  end
  
  # GET /tasks/update_date_task
  def update_date_task
    @task = Task.find(params[:id])
	@task.date = Time.at(params[:timestamp].to_i)
	@task.save
	
	render :partial => "update_date_task"
  end
  

end
